package com.sodaopen.study.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sodaopen.study.entity.AjaxResult;
import com.sodaopen.study.entity.ApiResult;
import com.sodaopen.study.entity.Media;
import com.sodaopen.study.service.MediaService;
import com.sodaopen.study.utils.UploadHelper;

@Controller
public class MediaController {

	@Value("${web.upload-path}")
    private String filePath;
	
	@Autowired
    private MediaService mediaService;

	@GetMapping("content/media")
    public String media(){
        return "media";
    }
    
	@GetMapping("/api/media/list")
	@ResponseBody
    public Object listCourse(@RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "15") Integer limit){

        ApiResult result = new ApiResult();
        try{
            Page<Media> pageContent = PageHelper.startPage(page, limit);
            List<Media> list = mediaService.findByParam();
            result.setCode(0);
            result.setCount(pageContent.getTotal());
            result.setData(list);
        }catch (Exception e){
            result.setCode(1);
            result.setMsg("数据请求失败");
        }
        return result;
    }
	
	@GetMapping("content/media/upload")
    public String mediaAdd(){
        return "media-add";
    }
	
	@PostMapping("content/media/upload")
    public String mediaUpload(MultipartFile file, String name, String type, Model model){
		boolean hideSuffix = false;
		if("v".equals(type)) {
			hideSuffix = true;
		}
		AjaxResult result = UploadHelper.saveFile(file, "f", filePath, hideSuffix);
		if(result.isSuccess()) {
			Media media = new Media();
			if(StringUtils.isEmpty(name)) {
				media.setName(file.getOriginalFilename());
			}else {
				media.setName(name);
			}
			media.setType(type);
			media.setUrl((String)result.getData());
			mediaService.saveMedia(media);
			model.addAttribute("msg", "文件\""+ file.getOriginalFilename() +"\"上传成功");
		}else {
			model.addAttribute("msg", "文件上传失败！");
		}
		
        return "media-add";
    }


	@PostMapping("content/wang/upload")
	@ResponseBody
	public Object wangUpload(MultipartFile file, String name, String type, Model model){
		Map<String, Object> result = new HashMap<>();

		AjaxResult ajax = UploadHelper.saveFile(file, "wang", filePath, false);

		// 返回给 wangEditor 的数据格式
		result.put("errno", ajax.isSuccess()?0:1 );
		result.put("data", new String[]{(String)ajax.getData()});

		return result;
	}
}
